package com.demo.xml.jaxb;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.junit.Test;

import com.demo.xml.jaxb.bean.ObjList;
import com.demo.xml.jaxb.bean.People;
import com.demo.xml.jaxb.bean.TestObj;

/**
 * 读取xml 生成java对象
 * @author chenliang
 *
 */
@SuppressWarnings("restriction")
public class JaxbReadXml {

	/**
	 * 读取xml文件返回对象
	 * clazz 返回对象类型 
	 * context xml文件路径
	 * @Description:TODO
	 * @author:chenliang
	 * @time:2018年5月19日 上午10:39:27
	 */
	public static <T> T readString(Class<T> clazz, String context)
			throws JAXBException, IOException {
		try {
			//读取xml文件
			InputStream inputStream = ClassLoader.getSystemResource(context)
					.openStream();
			
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			
			return (T) u.unmarshal(inputStream);
		} catch (JAXBException e) {
			throw e;
		}
	}

	/**
	 * 生成 java 对象  object
	 * @Description:TODO
	 * @author:chenliang
	 * @time:2018年5月18日 下午3:04:27
	 */
	@Test
	public void xml2Object() throws JAXBException, IOException {

		People People = JaxbReadXml.readString(People.class, "people.xml");
		System.out.println("xml2Object------------");
		System.out
				.println("姓名：" + People.getName() + "  年龄：" + People.getAge());
	}

	/**
	 * 生成 java 对象 list
	 * @Description:TODO
	 * @author:chenliang
	 * @time:2018年5月18日 下午3:03:48
	 */
	@Test
	public void xml2List() throws JAXBException, IOException {

		ObjList arrayObj = JaxbReadXml.readString(ObjList.class, "test.xml");
		System.out.println(arrayObj.getSize());

		System.out.println("xml2List------------");
		for (TestObj testObj : arrayObj.getObjList()) {
			System.out.println("姓名：" + testObj.getName() + "  出生日期："
					+ testObj.getBirthday());
		}
	}
}